\section{Interfacing Python with Other Languages}

\centeredlargetext{white}{black}{
Interfacing Python with Other Languages
}


\subsection{Wrapping C/C++ code in Python}

\begin{frame}
\frametitle{Wrapping C/C++ code in Python}
There are several options for wrapping C/C++ code in Python
\begin{itemize}
\item Calling the Python C API Manually (not for the faint of heart)
\item Interfacing with shared libraries using ctypes
\item Using Cython to generate C API calls (good for optimizing
  critical pieces of code)
\item Using SWIG to generate C API calls (good for wrapping larger
  libraries)
\item Using Boost.Python to bridge between Python and C++
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Working with the Python C API}
\begin{itemize}
\item Calling the C API directly allows you to get the most
  performance possible and have the greatest control of execution.
\item This is also one of the least easily maintainable methods.
\item For more information, see
  \url{http://docs.python.org/extending/extending.html}.
\item There is a simple example at \texttt{Examples/c-api-demonstration/cdemo.c}
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{A Note on the ctypes Module}
\begin{itemize}
\item \texttt{ctypes} is a built-in module that allows
  calling functions from shared libraries.
\item A more exhaustive explanation of what \texttt{ctypes} can do can be found here:
\url{http://docs.python.org/library/ctypes.html}.
\item For example, we can easily call the standard libc time function
  with the following snippet of code:
\end{itemize}
\lstlistingwithnumber{7}{17}{Examples/ctypes_example.py}
\begin{itemize}
\item This can be very useful, but doesn't feel as ``pythonic'' as some of the
other approaches.
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Cython}
\reference{More Info: \url{http://www.cython.org/}}
\begin{itemize}
\item Cython is a tool for ``compiling'' Python-like code into C to be
  compiled into python extension modules.
\item There are sets of annotations that can further optimize code
  through static typing, removal of bounds checking, etc.
\item An example of a \texttt{pyx} file and generated C file can be
  found in \texttt{Examples/cython}
\item Let's go through a simple example.
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Cython}
\begin{itemize}
\item This simple code compiled with Cython is 35\% faster.
\lstlistingwithnumber{0}{9}{Examples/cython/simplec.pyx}
\item By adding type declarations we can go a great deal faster, even
  with this simple example.
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Cython}
\begin{itemize}
\item This code compiled with Cython is 400\% faster, but we lose
  compatibility with Python through the calls to \texttt{cdef}.
\lstlistingwithnumber{0}{12}{Examples/cython/simple_opt.pyx}
\item We can do even better by typing the function call.
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{Cython}
\begin{itemize}
\item This code compiled with Cython is 15,000\% faster, but the calls
  are no able to raise Python errors.
\lstlistingwithnumber{0}{12}{Examples/cython/simple_opt_full.pyx}
\end{itemize}
\end{frame}

\setcounter{ipycommand}{0}

\begin{frame}[fragile]
\frametitle{Cython}
\begin{itemize}
\item Let's take a look at that timing on our virtual machines using
  %timeit in IPython.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) import simple

(*@\ipyprompt@*) import simplec

(*@\ipyprompt@*) import simple_opt

(*@\ipyprompt@*) import simple_opt_full

(*@\ipyprompt@*) %timeit for x in range(1,1001): simple.integrate_f(3, 5, x)
10 loops, best of 3: 137 ms per loop

(*@\ipyprompt@*) %timeit for x in range(1,1001): simplec.integrate_f(3, 5, x)
10 loops, best of 3: 79.8 ms per loop

(*@\ipyprompt@*) %timeit for x in range(1,1001): simple_opt.integrate_f(3, 5, x)
10 loops, best of 3: 55.6 ms per loop

(*@\ipyprompt@*) %timeit for x in range(1,1001): simple_opt_full.integrate_f(3, 5, x)
1000 loops, best of 3: 1.85 ms per loop
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{Cython}
\begin{itemize}
\item Here is an example of how to compile your cython into a loadable
  module (taken from \url{http://docs.cython.org/src/reference/compilation.html}).
\lstlistingwithnumber{0}{3}{Examples/cython/compile.sh}
\item This should give you an idea of the possibilities for rapid
  optimization with Cython. See \url{http://cython.org/} for more information.
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{SWIG}
\reference{More Info: \url{http://www.swig.org/}}
\begin{itemize}
\item SWIG is a great option for wrapping existing C/C++ code for many
  different languages, including Python
\item An example of swig usage can be found in \texttt{Examples/swig}
\item SWIG is generally used for large projects that need
  semi-automated wrapping for multiple languages (SimpleITK uses this
  for its wrapping).
\end{itemize}
\end{frame}

\begin{frame}[fragile]
\frametitle{SWIG}
\begin{itemize}
\item Here is an example of a C file we want to automatically wrap
  with SWIG
\end{itemize}
\lstset{language=C}
\lstlistingwithnumber{3}{21}{Examples/swig/example.c}
\end{frame}

\begin{frame}[fragile]
\frametitle{SWIG}
\begin{itemize}
\item In SWIG we define the interface or \texttt{.i} files
\end{itemize}
\lstlistingwithnumber{2}{15}{Examples/swig/example.i}
\end{frame}

\begin{frame}[fragile]
\frametitle{SWIG}
\begin{itemize}
\item To generate our example wrapping and build example.c itself, we
  run the following commands.
\end{itemize}
\lstlistingwithnumber{3}{5}{Examples/swig/compile.sh}
\begin{itemize}
\item Swig generates a shared library and python wrapper for importing
  it as shown below.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) import example

(*@\ipyprompt@*) example.fact(10)
(*@\ipyreturn@*) 3628800

\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{SWIG}
\begin{itemize}
\item This pattern can be used to wrap existing C and C++ libraries in
  a maintainable way.
\item There is also support for converting between STL types and
  Python types.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Boost.Python}
\reference{More Info: \url{http://www.boost.org/doc/libs/1_49_0/libs/python/doc/}}
\begin{itemize}
  \item Boost.Python is an alternative to SWIG.
  \begin{itemize}
    \item Only for making Python bindings (not multi-language)
    \item Designed to make wrapping of C++ easy.
    \item Handles C++ classes, virtual functions, inheritance, etc.
    \item Only involves writing C++ code (no interface files)
  \end{itemize}
  \pause
  \item To wrap the previous example code
\end{itemize}
\lstset{language=C++}
\begin{lstlisting}
#include <boost/python.hpp>

BOOST_PYTHON_MODULE(example)
{
    using namespace boost::python;
    scope().attr("My_variable") = My_variable;
    def("fact", fact);
    def("my_mod", my_mod);
    def("get_time", get_time);
}
\end{lstlisting}
\end{frame}


\subsection{Calling Legacy MATLAB Code in Python}

\centeredlargetext{white}{black}{Interfacing with Matlab}

\begin{frame}[fragile]
\frametitle{Interfacing with Matlab}
Any transition to Python from Matlab will require a means to utilize your previous Matlab code base.  There are several methods for doing this:
\begin{enumerate}

\item{Converting Matlab Code to Python}
  \begin{itemize}
    \item{\href{http://ompc.juricap.com/}{Open-Source Matlab-to-Python Compiler (OMPC) (\nolinkurl{ompc.juricap.com})}:}
      \begin{itemize}
      \item{Converts existing Matlab functions to Python, does not require Matlab license, but only works for simple functions}
      \end{itemize}
  \end{itemize}

\item{File Interchange with Matlab}
  \begin{itemize}
    \item{Load/Save .mats in Python:}
    \begin{itemize}
    \item{Scipy.io.$<loadmat/savemat>$ load/save .mats, does not require Matlab license, but may need to manipulate format after loading}
    \end{itemize}
  \end{itemize}

\item{Calling Legacy MATLAB Code from Python}
  \begin{itemize}
    \item{{\href{http://mlabwrap.sourceforge.net/}{Mlabwrap(\nolinkurl{mlabwrap.sourceforge.net})}}:}
      \begin{itemize}
      \item{Calls Matlab functions in manner similar to Matlab, does require Matlab license, and slower than Matlab}
      \end{itemize}
  \end{itemize}       
\end{enumerate}
\end{frame}

%*************************************************************************
\begin{frame}[fragile]
\frametitle{OMPC Example}
\reference{\url{http://ompc.juricap.com/download}}

Convert a Simple Matlab function that plots random numbers to Python

\begin{columns}[c] 
\column{0.4\textwidth}
  \lstset{title= Convert .m to .pym}
  \begin{lstlisting}
	(*@\ipyprompt@*) import ompc
	(*@\ipyprompt@*) import plot_rand_nums_ex1
	(*@\ipyprompt@*) plot_rand_nums_ex1(100)
	\end{lstlisting}	
	\includegraphics[width=\linewidth]{ScreenShot/plot_rand_result.png} 

\column{0.55\textwidth}
  \lstset{title=Examples/plot\_rand\_nums\_ex1.m}
	\lstlistingwithnumber{1}{7}{Examples/plot_rand_nums_ex1.m}  

	\lstset{title=Examples/plot\_rand\_nums\_ex1.pym}
	\lstlistingwithnumber{1}{13}{Examples/plot_rand_nums_ex1.pym}
\end{columns}	
\end{frame}	

%******************************************************************************
\begin{frame}[fragile]
\frametitle{Load/Save .mat Examples}
\reference{\url{}}

Create Structure in Matlab, save as .mat, and load into Python

%\begin{columns}[t]
%\column{0.45\textwidth}
\begin{matlabBlock}
>> xx.range= 1:11;
>> xx.name= 'vars1';
>> xx.cellvalues= {[15 16],'var1',[17 18],'var2'}
xx = 
         range: [1x11 double]
          name: 'vars1'
    cellvalues: {1x4 cell}
>> save('xx.mat','xx')
\end{matlabBlock}
    
%\column{0.45\textwidth}
\begin{pythonBlock}
> import scipy.io as sio
> xx= sio.loadmat('xx.mat')
> print xx
{'xx': array([[ ([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], [u'vars1'], 
			[[array([[15, 16]], dtype=uint8), array([u'var1'], 
      dtype='<U4'), array([[17, 18]], dtype=uint8), array([u'var2'], 
      dtype='<U4')]])]], 
      dtype=[('range', '|O4'), ('name', '|O4'), ('cellvalues', '|O4')]), 
      '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN64, 
      Created on: Tue May 29 12:53:43 2012', '__globals__': []}
\end{pythonBlock}
%\end{columns}
\end{frame}

%****************************************************************
\begin{frame}
\frametitle{Mlabwrap Example}
\reference{More Info: \url{http://mlabwrap.sourceforge.net/}}

\begin{itemize}
  \item Call Matlab's Surf() function from Python
  \lstlistingwithnumber{1}{11}{Examples/mlabwrap_ex1.py}
  \pause
  \begin{center}
  \includegraphics[width=0.3\linewidth]{ScreenShot/matlab_surf_ex1_results.png}
  \end{center}
  \pause
  \item Call Matlab's Singular Value Decomposition (svd) function
  \lstlistingwithnumber{13}{14}{Examples/mlabwrap_ex1.py}
\end{itemize}
\end{frame}
